package leetcode;

/**
 * @Author Gan
 * @Date 2021/5/9 22:21
 * @Description: 61
 */
public class RotateLinkedList {
    public static void main(String[] args) {
        ListNode head = new ListNode(1,null);
        head.next = new ListNode(2,null);
        System.out.println(rotateRight(head, 3));
    }

    public static ListNode rotateRight(ListNode head, int k) {
        if (head == null)
            return null;
        if (head.next == null)
            return head;
        ListNode p, pre,q;
        //循环移动k次即可
        for (int i = 0; i < k; i++) {
            pre = head;
            p = pre.next;
            while (p.next != null) {
                pre = p;
                p = p.next;
            }
            pre.next = null;
            p.next = head;
            head = p;
        }
        return head;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
